package com.youan.log.modules.audit.dataimport;

import com.youan.log.common.entity.ThreadTaskProgress;
import com.youan.log.common.service.IThreadTaskProgressService;
import com.youan.log.modules.audit.dataimport.bean.ImportTaskKey;
import com.youan.log.modules.audit.entity.ImportRecord;
import com.youan.log.modules.audit.service.IImportRecordService;
import org.springblade.core.tool.utils.SpringUtil;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

public class TableIndexCreator {

    private String sql;
    private Long importRecordId;
    private JdbcTemplate jdbcTemplate;

    public TableIndexCreator(String tableName, Long importRecordId) {
        DataSource dataSource = SpringUtil.getBean(DataSource.class);
        this.jdbcTemplate = new JdbcTemplate(dataSource);
        this.importRecordId = importRecordId;

        StringBuilder stringBuilder = new StringBuilder()
                .append("ALTER TABLE `log_audit_system`.`").append(tableName).append("` " )
                .append("ADD INDEX `rule_id_index`(`rule_id`),")
                .append("ADD INDEX `source_ip_index`(`source_ip`),")
                .append("ADD INDEX `destination_ip_index`(`destination_ip`)");
        this.sql = stringBuilder.toString();
    }

    public void create() {
        updateRecord();
        this.jdbcTemplate.execute(this.sql);
    }

    private void updateRecord() {
        IImportRecordService importRecordService = SpringUtil.getBean(IImportRecordService.class);
        ImportRecord importRecord = importRecordService.getById(this.importRecordId);

        ImportRecord updateRecord = new ImportRecord();
        updateRecord.setId(this.importRecordId);
        updateRecord.setTaskStatus(ImportTaskKey.THREAD_TASK_STATUS_CREATE_INDEX);
        importRecordService.updateById(updateRecord);

        IThreadTaskProgressService threadTaskProgressService = SpringUtil.getBean(IThreadTaskProgressService.class);
        ThreadTaskProgress updateThreadTaskProgress = new ThreadTaskProgress();
        updateThreadTaskProgress.setId(importRecord.getTaskId());
        updateThreadTaskProgress.setTaskStatus(ImportTaskKey.THREAD_TASK_STATUS_CREATE_INDEX);
        updateThreadTaskProgress.setTaskStatusText(ImportTaskKey.THREAD_TASK_STATUS_CREATE_INDEX_TEXT);
        threadTaskProgressService.updateById(updateThreadTaskProgress);
    }
}
